package org.jash.imdemo.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.timepicker.MaterialTimePicker;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.jash.imdemo.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;


public class MineFragment extends Fragment {
    private ActivityResultLauncher<Intent> launcher;
    private ImageView header;
    private NavigationView nav;
    private ActivityResultLauncher<String> getHeader;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private CharSequence[] items;
    private MaterialToolbar toolbar;
    private DrawerLayout drawer;
    public MineFragment() {
        super(R.layout.fragment_mine);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), intent -> {
            Intent data = intent.getData();
            int resultCode = intent.getResultCode();
            if (resultCode == Activity.RESULT_OK && data != null) {
                Bundle bundle = data.getExtras();
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(requireContext(), "解析结果:" + result, Toast.LENGTH_LONG).show();
                    new Thread(() -> {
                        try {
                            EMClient.getInstance().contactManager().addContact(result, "请求添加好友");
                        } catch (HyphenateException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(requireContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            } else{
                Toast.makeText(requireContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
            }
        });
        getHeader = registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
            header.setImageURI(uri);
        });
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        header = view.findViewById(R.id.header);
        header.setOnClickListener(v -> getHeader.launch("image/*"));
        nav = view.findViewById(R.id.nav);
        toolbar = view.findViewById(R.id.toolbar);
        drawer = view.findViewById(R.id.drawer);
        nav.setNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.qrcode) {
                ImageView imageView = new ImageView(requireContext());
                Bitmap image = CodeUtils.createImage(EMClient.getInstance().getCurrentUser(), 400, 400, null);
                imageView.setImageBitmap(image);
                new MaterialAlertDialogBuilder(requireContext())
                        .setView(imageView)
                        .show();
            } else if (item.getItemId() == R.id.logout) {
                EMClient.getInstance().logout(false, new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        requireActivity().runOnUiThread(() -> requireActivity().finish());
                    }

                    @Override
                    public void onError(int code, String error) {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "退出失败, 原因: " + error, Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            } else if (item.getItemId() == R.id.birthday) {
                try {
                    Date date = sdf.parse(item.getTitle().toString().split(":")[1].trim());
                    MaterialDatePicker<Long> picker = MaterialDatePicker.Builder.datePicker()
                            .setSelection(date.getTime())
                            .setTitleText("请选择生日")
                            .build();
                    picker.addOnPositiveButtonClickListener(selection -> {
                        item.setTitle("生日: " + sdf.format(new Date(selection)));
                    });
                    picker.show(getChildFragmentManager(), null);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            } else if (item.getItemId() == R.id.gender) {
                items = new CharSequence[]{"男", "女"};
                new MaterialAlertDialogBuilder(requireContext())
                        .setItems(items, (dialog, which) -> {
                            item.setTitle("性别: " + items[which]);
                        })
                        .setTitle("请选择性别")
                        .show();
            }
            return true;
        });
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(requireActivity(), drawer, toolbar, 0, 0);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
//        view.findViewById(R.id.logout).setOnClickListener(v -> {
//            EMClient.getInstance().logout(false, new EMCallBack() {
//                @Override
//                public void onSuccess() {
//                    requireActivity().runOnUiThread(() -> requireActivity().finish());
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "退出失败, 原因: " + error, Toast.LENGTH_SHORT).show());
//                }
//
//                @Override
//                public void onProgress(int progress, String status) {
//
//                }
//            });
//        });
//        view.findViewById(R.id.qrcode).setOnClickListener(v -> {
//            ImageView imageView = new ImageView(requireContext());
//            Bitmap image = CodeUtils.createImage(EMClient.getInstance().getCurrentUser(), 400, 400, null);
//            imageView.setImageBitmap(image);
//            new MaterialAlertDialogBuilder(requireContext())
//                    .setView(imageView)
//                    .show();
//        });
//        view.findViewById(R.id.scanner).setOnClickListener(v -> {
//            launcher.launch(new Intent(requireContext(), CaptureActivity.class));
//        });
    }
}